package com.mezz.bones.framework.notification.sms.impl;

import com.alibaba.fastjson.JSONObject;
import com.mezz.bones.framework.base.exception.CodeSendErrorException;
import com.mezz.bones.framework.notification.sms.ISmsService;
import com.mezz.bones.framework.notification.sms.properties.SmsProperties;
import com.mezz.bones.framework.notification.sms.request.SmsSendRequest;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author mezz
 * @date 2022-05-04 09:25
 * @description:
 */
@Service
@Slf4j
public class TxSmsService implements ISmsService {

    @Resource
    private SmsProperties smsProperties;

    @Override
    public String tag() {
        return TX;
    }

    @Override
    public void singleSend(SmsSendRequest request) throws CodeSendErrorException {

        SmsProperties.TxSms txSmsProperties = smsProperties.getTxSms();

        // 配置腾讯云客户端凭证
        Credential cred = new Credential(txSmsProperties.getAppKey(), txSmsProperties.getAppKey());

        SmsClient client = new SmsClient(cred, txSmsProperties.getRegion());

        // 配置短信请求
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppId(txSmsProperties.getAppId().toString());
        sendSmsRequest.setSignName(request.getSignName());
        sendSmsRequest.setTemplateId(request.getTemplateId());
        sendSmsRequest.setPhoneNumberSet(new String[]{request.getNationCode() + request.getPhone()});
        sendSmsRequest.setTemplateParamSet(request.getParams()); // 根据具体情况设置模板参数

        try {
            // 发送短信
            SendSmsResponse res = client.SendSms(sendSmsRequest);
            log.debug("TxSmsService singleSend req[{}], res[{}]", JSONObject.toJSONString(sendSmsRequest), JSONObject.toJSONString(res));

            for (SendStatus status : res.getSendStatusSet()) {
                if (!"Ok".equalsIgnoreCase(status.getCode())) {
                    log.debug("Failed to send SMS: " + status.getCode() + " - " + status.getMessage());
                }
            }

        } catch (TencentCloudSDKException e) {
            log.error("Failed to send SMS TencentCloudSDKException: " + e.getMessage());
        }
    }

    @Override
    public void multiSend(SmsSendRequest smsSendRequest) throws CodeSendErrorException {

    }
}
